package com.tsoj.utils;

import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

/**
 * api签名认证
 */
@Component
public class ApiSignatureAuth {

    private static String SECRET_KEY = "tsoj";
    //生成签名
    public static String generateSignature(Map<String, String> params){
        ArrayList<String> sortedKeys = new ArrayList<>(params.keySet());
        Collections.sort(sortedKeys);

        StringBuilder paramStr = new StringBuilder();
        for (String key : sortedKeys){
            paramStr.append(key).append("=").append(params.get(key)).append("&");
        }
        //拼接密钥
        paramStr.append("secretKey=").append(SECRET_KEY);

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(paramStr.toString().getBytes());

            StringBuilder hexStr = new StringBuilder();
            for(byte b:digest){
                String hex = Integer.toHexString(0xff & b);
                if(hex.length() == 1){
                    hexStr.append('0');
                }
                hexStr.append(hex);
            }
            return hexStr.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
